import pagesJson from '@/pages.json'
import defaultImage from '@/static/logo.png'

console.log(pagesJson)

/** 判断当前页面是否是tabbar页  */
export const getIsTabbar = () => {
  if (!Object.keys(pagesJson).includes('tabBar')) {
    return false
  }
  const pages = getCurrentPages()
  const lastPage = getArrElementByIdx(pages, -1)
  const currPath = lastPage.route
  return !!pagesJson.tabBar.list.find((e) => e.pagePath === currPath)
}

/**
 * 获取当前页面路由的 path 路劲和 redirectPath 路径
 * path 如 ‘/pages/login/index’
 * redirectPath 如 ‘/pages/demo/base/route-interceptor’
 */
export const currRoute = () => {
  const pages = getCurrentPages()
  console.log('pages:', pages)

  const lastPage = getArrElementByIdx(pages, -1)
  const currRoute = lastPage.$page
  // console.log('lastPage.$page:', currRoute)
  // console.log('lastPage.$page.fullpath:', currRoute.fullPath)
  // console.log('lastPage.$page.options:', currRoute.options)
  // console.log('lastPage.options:', (lastPage as any).options)
  // 经过多端测试，只有 fullPath 靠谱，其他都不靠谱
  const { fullPath } = currRoute
  console.log(fullPath)
  // eg: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor (小程序)
  // eg: /pages/login/index?redirect=%2Fpages%2Froute-interceptor%2Findex%3Fname%3Dfeige%26age%3D30(h5)
  return getUrlObj(fullPath)
}

const ensureDecodeURIComponent = (url) => {
  if (url.startsWith('%')) {
    return ensureDecodeURIComponent(decodeURIComponent(url))
  }
  return url
}
/**
 * 解析 url 得到 path 和 query
 * 比如输入url: /pages/login/index?redirect=%2Fpages%2Fdemo%2Fbase%2Froute-interceptor
 * 输出: {path: /pages/login/index, query: {redirect: /pages/demo/base/route-interceptor}}
 */
export const getUrlObj = (url) => {
  const [path, queryStr] = url.split('?')
  console.log(path, queryStr)

  let query = null
  if (queryStr) {
    query = {}
    queryStr.split('&').forEach((item) => {
      const [key, value] = item.split('=')
      console.log(key, value)
      query[key] = ensureDecodeURIComponent(value) // 这里需要统一 decodeURIComponent 一下，可以兼容h5和微信y
    })
  }
  return { path, query }
}
/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 这里设计得通用一点，可以传递key作为判断依据，默认是 needLogin, 与 route-block 配对使用
 * 如果没有传 key，则表示所有的pages，如果传递了 key, 则表示通过 key 过滤
 */
export const getAllPages = (key = 'needLogin') => {
  // 这里处理主包
  const pages = [
    ...pagesJson.pages
      .filter((page) => !key || page[key])
      .map((page) => ({
        ...page,
        path: `/${page.path}`,
      })),
  ]
  // 这里处理分包
  const subPages = []
  pagesJson.subPackages.forEach((subPageObj) => {
    // console.log(subPageObj)
    const { root } = subPageObj

    subPageObj.pages
      .filter((page) => !key || page[key])
      .forEach((page) => {
        subPages.push({
          ...page,
          path: `/${root}/${page.path}`,
        })
      })
  })
  const result = [...pages, ...subPages]
  console.log(`getAllPages by ${key} result: `, result)
  return result
}

/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 只得到 path 数组
 */
export const getNeedLoginPages = () =>
  getAllPages('needLogin').map((page) => page.path)

/**
 * 得到所有的需要登录的pages，包括主包和分包的
 * 只得到 path 数组
 */
export const needLoginPages = getAllPages('needLogin').map((page) => page.path)

export const getArrElementByIdx = (arr, index) => {
  if (index < 0) return arr[arr.length + index]
  if (index >= arr.length) return undefined
  return arr[index]
}

// 路由跳转
export const uniNavigateTo = (url) => uni.navigateTo({ url })

// 上一页是否需要刷新
export const prevPageNeedRefresh = (needRefresh = true) => {
  const pages = getCurrentPages()
  const prevPage = pages[pages.length - 2]
  prevPage.needRefresh = needRefresh
}

// 当前页面是否需要刷新
export const currentPageNeedRefresh = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage?.needRefresh
}

// 根据文件后缀判断文件类型
export const judgeFileType = (filePath) => {
  const noQueryPath = filePath?.split('?')[0] // 文件的地址后面可能带参数(xxx.png?sign=yyy)
  const suffix = noQueryPath?.split('.').pop().toLowerCase()
  const imageSuffix = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'raw'] // 图片类型
  const videoSuffix = ['mp4', 'mov', 'wmv', 'flv', 'avi', 'webm', 'mkv'] // 视频类型
  let type = ''
  if (videoSuffix.includes(suffix)) {
    type = 'video'
  } else if (imageSuffix.includes(suffix)) {
    type = 'image'
  } else {
    type = ''
  }
  return {
    type,
    src: filePath,
  }
}

// 回完整的文件url
const baseURL = import.meta.env.VITE_SERVER_BASEURL
const isDev = import.meta.env.DEV
export const returnFullUrl = (url) => {
  if (url.startsWith('http')) {
    return url
  }
  return isDev ? `${baseURL}/${url}` : url
}

// 格式化 url 字符串（url 是通过“,”连接的）
// const defaultImage = 'https://registry.npmmirror.com/wot-design-uni-assets/*/files/moon.jpg'

export const formatUrlString = (urlString, needDefault = true) => {
  let fullUrlArr = []
  if (urlString) {
    // const urlArr = urlString.split(',')
    // fullUrlArr = urlArr.map((item) => returnFullUrl(item))
    fullUrlArr = urlString?.split(',')
  } else if (needDefault) {
    fullUrlArr = [defaultImage]
  }
  return fullUrlArr
}

// 如果存在 liveUrl 就显示 liveUrl，如果有图片就显示图片，
// 如果 liveUrl 为空，就显示 coverUrl
// 如果 coverUrl 也为空，就显示默认图片
export const judgeShowImage = (coverUrl, liveUrl) => {
  if (liveUrl && liveUrl.length > 0) {
    const urlArr = liveUrl?.split(',')
    const findUrl = urlArr.find((item) => judgeFileType(item).type === 'image')
    if (findUrl) {
      return returnFullUrl(findUrl)
    }
  }
  if (coverUrl && coverUrl.length > 0) {
    return returnFullUrl(formatUrlString(coverUrl, false)[0])
  }
  return defaultImage
}

// 根据字典，返回状态的颜色
export const returnStatusColor = (status, activityDeclareStatus = []) => {
  let color = ''
  for (let i = 0; i < activityDeclareStatus.length; i++) {
    if (activityDeclareStatus[i].value === status) {
      color = activityDeclareStatus[i].color
      break
    }
  }
  console.log('returnStatusColor', color)
  return color
}

export const isVideo = (type) => {
  return ['video', 'mp4', 'avi', 'mov', 'mkv', 'flv', 'wmv'].includes(type)
}

// 扁平化数组
export const flattenTree = (tree) => {
  const result = []

  function recursiveFlatten(node) {
    result.push(node)
    if (node.children) {
      node.children.forEach(recursiveFlatten)
    }
  }

  tree.forEach(recursiveFlatten)
  return result
}

// 返回上一页
export function goBack(delta = 1) {
  // 如果没有上一级界面则返回首页
  const pages = getCurrentPages()
  if (pages.length <= delta) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
  } else {
    uni.navigateBack({
      delta,
    })
  }
}

// 电话号码脱敏
export const phoneMask = (phone) => {
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 人的姓名脱敏
export const nameMask = (name) => {
  // 检查输入是否为空或非字符串
  if (!name || typeof name !== 'string') {
    return name
  }

  // 去除首尾空格
  name = name.trim()

  // 如果姓名长度小于等于1，直接返回*
  if (name.length <= 1) {
    return '*'
  }

  // 如果姓名长度为2，保留首尾字符，中间用*代替
  if (name.length === 2) {
    return name.charAt(0) + '*'
  }

  // 如果姓名长度大于2，保留首尾字符，中间用*代替
  const firstChar = name.charAt(0)
  const lastChar = name.charAt(name.length - 1)
  const middleCount = name.length - 2
  const maskedMiddle = '*'.repeat(middleCount)

  return firstChar + maskedMiddle + lastChar
}

/**
 * 验证手机号码是否正确
 * @param {string} phone - 手机号码
 * @returns {boolean} - 返回true表示手机号码格式正确，false表示格式错误
 */
export const isValidPhone = (phone) => {
  // 检查输入是否为空或非字符串
  if (!phone || typeof phone !== 'string') {
    return false
  }

  // 中国手机号码正则表达式
  // 说明：
  // ^1 - 必须以1开头
  // [3-9] - 第二位必须是3-9之间的数字
  // \d{9}$ - 后面跟着9个数字
  const phoneRegex = /^1[3-9]\d{9}$/

  return phoneRegex.test(phone)
}
